const events = require("events");
const net = require("net");
const channel = new events.EventEmitter();

channel.clients = {};
channel.subscriptions = {};

channel.on('join', function (id, client) {
    this.clients[id] = client;
    this.subscriptions[id] = (sendId, message) => {
        if (id != sendId) {
            this.clients[id].write(message);

        }
    }

    this.on('broadcast', this.subscriptions[id]);

}).on('leave',function (id) {
    channel.removeListener('broadcast', this.subscriptions[id]);
    const mesage = `${id} has left the chatroom \n`;
    channel.emit('broadcast','', mesage);
}).on('error',(err)=>{
    console.log(err)
}).on('shutdown',() => {
    channel.emit('broadcast','', 'The Server has shut down');
    channel.removeAllListeners('broadcast');
});

const server = net.createServer(client => {
    const id = `${client.remoteAddress}:${client.remotePort}`;
    channel.emit('join', id, client);
    client.on('data', data => {
        data = data.toString();
        if (data === 'shutdown\r\n') {
            channel.emit('shutdown');
        }
        channel.emit('broadcast', id, data);
    }).on('close', () => {
        channel.emit('leave', id);
    });
}).listen(8888);